import platform
import psutil
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QColor
from qfluentwidgets import (
    FluentWindow, NavigationItemPosition, FluentIcon,
    TitleLabel, BodyLabel, StrongBodyLabel, PushButton,
    CardWidget, ScrollArea, VBoxLayout
)

from window.log_analyzer.log_analyzer import LogAnalyzer
from window.process_manager.process_manager import ProcessManager
from window.resource_monitor.resource_monitor import ResourceMonitor
from window.scanner.scanner import Scanner
from window.user_manager.user_manager import UserManager


class MainWindow(FluentWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("系统性能监控")
        self.resize(1400, 900)
        self.setMinimumSize(1000, 700)

        self.get_hardware_info()
        self.setup_navigation()
        self.setup_pages()
        self.setStyleSheet("background-color: white;")

    def get_hardware_info(self):
        try:
            self.cpu_name = platform.processor() or "未知处理器"
            if not self.cpu_name or self.cpu_name.strip() == "":
                import subprocess
                try:
                    result = subprocess.run(['wmic', 'cpu', 'get', 'name'], capture_output=True, text=True)
                    lines = result.stdout.strip().split('\n')
                    if len(lines) > 1:
                        self.cpu_name = lines[1].strip()
                except:
                    self.cpu_name = f"{psutil.cpu_count()} 核心处理器"
            memory = psutil.virtual_memory()
            self.memory_total = f"{memory.total / (1024 ** 3):.1f} GB"
            self.system_name = f"{platform.system()} {platform.release()}"
            self.computer_name = platform.node()
        except Exception as e:
            print(f"获取硬件信息时出错: {e}")
            self.cpu_name = "未知处理器"
            self.memory_total = "未知内存"
            self.system_name = "未知系统"
            self.computer_name = "本机"

    def setup_navigation(self):
        # 添加导航项
        # dashboard_page = self.create_dashboard_page()
        # dashboard_page.setObjectName("dashboard")
        # self.addSubInterface(
        #     dashboard_page,
        #     FluentIcon.SETTING,
        #     "系统概览",
        #     NavigationItemPosition.TOP
        # )

        resource_monitor = ResourceMonitor()
        resource_monitor.setObjectName("resource_monitor")
        self.addSubInterface(
            resource_monitor,
            FluentIcon.SPEED_HIGH,
            "资源监控",
            NavigationItemPosition.TOP
        )

        # vulnerability_page = self.create_placeholder_page("漏洞扫描")
        # vulnerability_page.setObjectName("vulnerability")
        # self.addSubInterface(
        #     vulnerability_page,
        #     FluentIcon.SEARCH,
        #     "漏洞扫描",
        #     NavigationItemPosition.TOP
        # )
        # 替换漏洞扫描占位符页面
        vulnerability_page = Scanner()
        vulnerability_page.setObjectName("vulnerability")
        self.addSubInterface(
            vulnerability_page,
            FluentIcon.SEARCH,
            "漏洞扫描",
            NavigationItemPosition.TOP
        )

        # process_page = self.create_placeholder_page("进程管理")
        # process_page.setObjectName("process")
        # self.addSubInterface(
        #     process_page,
        #     FluentIcon.APPLICATION,
        #     "进程管理",
        #     NavigationItemPosition.TOP
        # )
        # 替换原来的进程管理占位页面
        process_page = ProcessManager()
        process_page.setObjectName("process")
        process_page.hide_loading_indicator()
        self.addSubInterface(
            process_page,
            FluentIcon.APPLICATION,
            "进程管理",
            NavigationItemPosition.TOP
        )

        # log_page = self.create_placeholder_page("日志分析")
        # log_page.setObjectName("log")
        # self.addSubInterface(
        #     log_page,
        #     FluentIcon.DOCUMENT,
        #     "日志分析",
        #     NavigationItemPosition.TOP
        # )
        # 替换原有的日志分析占位页面
        log_page = LogAnalyzer()
        log_page.setObjectName("log")
        self.addSubInterface(
            log_page,
            FluentIcon.DOCUMENT,
            "日志分析",
            NavigationItemPosition.TOP
        )

        # user_page = self.create_placeholder_page("用户权限")
        # user_page.setObjectName("user")
        # self.addSubInterface(
        #     user_page,
        #     FluentIcon.PEOPLE,
        #     "用户权限",
        #     NavigationItemPosition.TOP
        # )
        # 替换为实际的用户权限审查页面
        user_page = UserManager()
        user_page.setObjectName("user")
        self.addSubInterface(
            user_page,
            FluentIcon.PEOPLE,
            "用户权限",
            NavigationItemPosition.TOP
        )

        # report_page = self.create_placeholder_page("报告生成")
        # report_page.setObjectName("report")
        # self.addSubInterface(
        #     report_page,
        #     FluentIcon.SETTING,
        #     "报告生成",
        #     NavigationItemPosition.TOP
        # )
        #
        # # 在底部添加刷新按钮（作为设置项）
        # refresh_widget = QWidget()
        # refresh_widget.setObjectName("refresh")
        # refresh_layout = QVBoxLayout(refresh_widget)
        # refresh_layout.setContentsMargins(20, 20, 20, 20)
        #
        # refresh_btn = PushButton("刷新数据")
        # refresh_btn.setIcon(FluentIcon.SYNC)
        # refresh_btn.clicked.connect(self.refresh_data)
        # refresh_layout.addWidget(refresh_btn)
        #
        # self.addSubInterface(
        #     refresh_widget,
        #     FluentIcon.SYNC,
        #     "刷新数据",
        #     NavigationItemPosition.BOTTOM
        # )

    def create_dashboard_page(self):
        dashboard_page = ScrollArea()
        dashboard_widget = QWidget()
        dashboard_page.setWidget(dashboard_widget)
        dashboard_page.setWidgetResizable(True)

        layout = VBoxLayout(dashboard_widget)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(20)

        # 页面标题
        title = TitleLabel("系统性能仪表盘")
        layout.addWidget(title)

        # 系统信息卡片
        system_card = CardWidget()
        system_layout = VBoxLayout(system_card)
        system_layout.setContentsMargins(20, 20, 20, 20)

        system_title = StrongBodyLabel("系统信息")
        system_layout.addWidget(system_title)

        system_info = BodyLabel(f"系统: {self.system_name}")
        system_layout.addWidget(system_info)

        computer_info = BodyLabel(f"计算机名: {self.computer_name}")
        system_layout.addWidget(computer_info)

        layout.addWidget(system_card)

        # 硬件信息卡片
        hardware_card = CardWidget()
        hardware_layout = VBoxLayout(hardware_card)
        hardware_layout.setContentsMargins(20, 20, 20, 20)

        hardware_title = StrongBodyLabel("硬件信息")
        hardware_layout.addWidget(hardware_title)

        cpu_info = BodyLabel(f"CPU: {self.truncate_text(self.cpu_name, 50)}")
        hardware_layout.addWidget(cpu_info)

        memory_info = BodyLabel(f"内存: {self.memory_total}")
        hardware_layout.addWidget(memory_info)

        layout.addWidget(hardware_card)

        # 占位符
        placeholder = BodyLabel("系统概览功能正在开发中...")
        placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(placeholder)

        layout.addStretch()

        return dashboard_page

    def create_placeholder_page(self, page_name):
        page = ScrollArea()
        page_widget = QWidget()
        page.setWidget(page_widget)
        page.setWidgetResizable(True)

        layout = VBoxLayout(page_widget)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(20)

        # 页面标题
        title = TitleLabel(f"{page_name}模块")
        layout.addWidget(title)

        # 功能卡片
        card = CardWidget()
        card_layout = VBoxLayout(card)
        card_layout.setContentsMargins(20, 20, 20, 20)

        placeholder = BodyLabel(f"{page_name}功能正在开发中...")
        placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
        card_layout.addWidget(placeholder)

        layout.addWidget(card)
        layout.addStretch()

        return page

    def setup_pages(self):
        # 这个方法保留用于兼容性，实际页面设置在setup_navigation中完成
        pass

    def truncate_text(self, text, max_length):
        if len(text) > max_length:
            return text[:max_length - 3] + "..."
        return text

    def refresh_data(self):
        print("正在刷新数据...")
        self.get_hardware_info()
        # 可以在这里添加刷新界面数据的逻辑